<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DeepSeek Chat Clone</title>
    <style>
        /* 深色系官方风格 */
        :root {
            --primary-color: #10a37f;
            --bg-color: #343541;
            --sidebar-bg: #202123;
            --message-bg-user: #444654;
            --message-bg-bot: #343541;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            display: flex;
            height: 100vh;
            background: var(--bg-color);
            color: #d1d5db;
            font-family: -apple-system, system-ui, sans-serif;
        }

        /* 左侧边栏 */
        .sidebar {
            width: 260px;
            background: var(--sidebar-bg);
            padding: 12px;
            display: flex;
            flex-direction: column;
        }

        .new-chat-btn {
            padding: 12px;
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            margin-bottom: 12px;
        }

        .history-list {
            flex: 1;
            overflow-y: auto;
        }

        .chat-item {
            padding: 12px;
            border-radius: 6px;
            margin: 4px 0;
            cursor: pointer;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .chat-item:hover {
            background: rgba(255,255,255,0.1);
        }

        /* 主聊天区域 */
        .main-chat {
            flex: 1;
            display: flex;
            flex-direction: column;
            position: relative;
        }

        #chat-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
        }

        .message {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            border-radius: 8px;
            line-height: 1.6;
        }

        .user-message {
            background: var(--message-bg-user);
            margin-left: auto;
        }

        .bot-message {
            background: var(--message-bg-bot);
            margin-right: auto;
        }

        /* 输入区域 */
        #input-container {
            padding: 20px;
            background: var(--sidebar-bg);
            display: flex;
            gap: 12px;
        }

        #user-input {
            flex: 1;
            padding: 12px;
            background: rgba(255,255,255,0.05);
            border: 1px solid rgba(255,255,255,0.1);
            border-radius: 8px;
            color: white;
            font-size: 16px;
        }

        #send-btn {
            padding: 12px 24px;
            background: var(--primary-color);
            border: none;
            border-radius: 8px;
            color: white;
            cursor: pointer;
        }

        /* 加载动画 */
        .loading-dots::after {
            content: '';
            display: inline-block;
            animation: dots 1s infinite;
        }

        @keyframes dots {
            0%, 20% { content: '.'; }
            40% { content: '..'; }
            60% { content: '...'; }
            80%, 100% { content: ''; }
        }
    </style>
</head>
<body>
    <!-- 左侧边栏 -->
    <div class="sidebar">
        <button class="new-chat-btn" onclick="createNewChat()">+ 新对话</button>
        <div class="history-list" id="historyList"></div>
    </div>

    <!-- 主聊天区域 -->
    <div class="main-chat">
        <div id="chat-container"></div>
        <div id="input-container">
            <input type="text" id="user-input" placeholder="输入消息..." autocomplete="off">
            <button id="send-btn" onclick="sendMessage()">发送</button>
        </div>
    </div>

    <script>
        // 对话管理逻辑
        let currentChatId = null;
        let chats = JSON.parse(localStorage.getItem('chats') || '[]');

        // 初始化加载历史
        function initHistory() {
            const historyList = document.getElementById('historyList');
            historyList.innerHTML = '';
            
            chats.forEach(chat => {
                const item = document.createElement('div');
                item.className = 'chat-item';
                item.textContent = chat.messages[0]?.content.substring(0, 30) || '新对话';
                item.onclick = () => loadChat(chat.id);
                historyList.appendChild(item);
            });

            if (chats.length === 0) createNewChat();
            else loadChat(chats[0].id);
        }

        // 创建新对话
        function createNewChat() {
            currentChatId = Date.now().toString();
            const newChat = {
                id: currentChatId,
                messages: [],
                timestamp: new Date().toISOString()
            };
            chats.unshift(newChat);
            saveChats();
            initHistory();
            clearChatContainer();
        }

        // 加载对话
        function loadChat(chatId) {
            currentChatId = chatId;
            const chat = chats.find(c => c.id === chatId);
            clearChatContainer();
            chat.messages.forEach(msg => {
                appendMessage(msg.role === 'user' ? 'user' : 'bot', msg.content);
            });
        }

        // 保存到 localStorage
        function saveChats() {
            localStorage.setItem('chats', JSON.stringify(chats));
        }

        // 清空聊天区域
        function clearChatContainer() {
            document.getElementById('chat-container').innerHTML = '';
        }

        // 消息处理逻辑
        function appendMessage(role, content) {
            const container = document.getElementById('chat-container');
            const msgDiv = document.createElement('div');
            msgDiv.className = `message ${role}-message`;
            msgDiv.innerHTML = content;
            container.appendChild(msgDiv);
            container.scrollTop = container.scrollHeight;
        }

        // 发送消息
        async function sendMessage() {
            const input = document.getElementById('user-input');
            const message = input.value.trim();
            if (!message) return;

            input.value = '';
            appendMessage('user', message);

            // 显示加载状态
            const loadingMsg = document.createElement('div');
            loadingMsg.className = 'message bot-message loading-dots';
            loadingMsg.textContent = '思考中';
            document.getElementById('chat-container').appendChild(loadingMsg);

            try {
                // 调试：打印当前对话的所有消息
                console.log('[DEBUG] Current Chat Messages:', JSON.stringify(getCurrentChat().messages, null, 2));

                // 安全构建请求体
                const requestBody = {
                    question: message,
                    history: getCurrentChat().messages.map(msg => ({
                        role: msg.role || 'user', // 默认角色
                        content: (msg.content || '').toString() // 处理 undefined
                    }))
                };

                console.log('[DEBUG] Request Body:', JSON.stringify(requestBody, null, 2));

                const response = await fetch('deepseek.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(requestBody)
                });

                const data = await response.json();
                loadingMsg.remove();

                if (data.error) {
                    appendMessage('bot', `错误: ${data.error}`);
                } else {
                    appendMessage('bot', data.answer);
                    saveMessageToHistory('user', message);
                    saveMessageToHistory('assistant', data.answer);
                }
            } catch (error) {
                loadingMsg.remove();
                appendMessage('bot', '请求失败，请检查网络');
                console.error('Error:', error);
            }
        }

        // 辅助函数
        function getCurrentChat() {
            return chats.find(c => c.id === currentChatId);
        }

        function saveMessageToHistory(role, content) {
            const chat = getCurrentChat();
            chat.messages.push({ role, content });
            saveChats();
        }

        // 初始化
        initHistory();

        // 回车发送
        document.getElementById('user-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    </script>
</body>
</html>